//
//  LoginViewController.m
//  SXH
//
//  Created by 房 国生 on 15/7/10.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "LoginViewController.h"
#import "MeProfileViewController.h"
#import "CommonService.h"
#import "LPUtils.h"
#import "UserEntity.h"
#import "RegisterViewController.h"
#import "AppDelegate.h"
#import "RessetViewController.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "LPUtils.h"
#import <ShareSDK/ShareSDK.h>
#import "BindMobileViewController.h"

//腾讯开放平台（对应QQ和QQ空间）SDK头文件
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>

//微信SDK头文件
#import "WXApi.h"

//新浪微博sdk
#import "WeiboSDK.h"


@interface LoginViewController ()
@property (nonatomic, strong) IBOutlet UITextField *textFieldPhone;
@property (nonatomic, strong) IBOutlet UITextField *textFieldNumber;
@property (strong, nonatomic) IBOutlet UIButton *btnSMS;
@property (weak, nonatomic) IBOutlet UIButton *btnLogin;
@property (nonatomic)BOOL isPwdLogin;
@property (nonatomic, strong) NSTimer* timer1;
@property (nonatomic, strong) NSString *verifyCode;
@property (nonatomic, strong) NSString *firstLogin;
@property (weak, nonatomic) IBOutlet UILabel *mobileTitle;
@property (weak, nonatomic) IBOutlet UILabel *yanzhenmaLabel;
@property (weak, nonatomic) IBOutlet UIView *verifyLine;
@property (weak, nonatomic) IBOutlet UILabel *noticeLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *textFieldtoRight;
@property (nonatomic, strong) UIView *bottomLine;
@end

@implementation LoginViewController
@synthesize textFieldNumber, textFieldPhone, btnSMS, btnLogin;
@synthesize timer1, verifyCode, firstLogin;
@synthesize wrapperMainVC, mainVC, meVC;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"账号登录";
    self.view.backgroundColor = HEXCOLOR(0xededed);
    self.bottomLine = [[UIView alloc]init];
    [self.view addSubview:self.bottomLine];
    self.bottomLine.backgroundColor = GreenColor;
    self.isPwdLogin = YES;
    [btnSMS.layer setMasksToBounds:YES];
    [btnSMS.layer setCornerRadius:5.0]; //设置矩形四个圆角半径
    [btnLogin.layer setMasksToBounds:YES];
    [btnLogin.layer setCornerRadius:5.0]; //设置矩形四个圆角半径


    [textFieldNumber addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.textFieldPhone.keyboardType = UIKeyboardTypePhonePad;
    [btnLogin setBackgroundColor:GreenColor];
    
    [self showOrHideShareIcon];
}

/**
 * 判断是否安装第三方
 */
- (void)showOrHideShareIcon {
    UIButton *button1 = [self.view viewWithTag:1000];
    UIButton *button2 = [self.view viewWithTag:1001];
    UIButton *button3 = [self.view viewWithTag:1002];
    //仅安装微信
    if ([WXApi isWXAppInstalled] && ![QQApi isQQInstalled] && ![WeiboSDK isWeiboAppInstalled]) {
        button1.transform = CGAffineTransformMakeTranslation(100, 0);
        button2.hidden = YES;
        button3.hidden = YES;
    }
    //仅安装qq
    if (![WXApi isWXAppInstalled] && [QQApi isQQInstalled] && ![WeiboSDK isWeiboAppInstalled]) {
        button1.hidden = YES;
        button3.hidden = YES;
    }
    //仅安装微博
    if (![WXApi isWXAppInstalled] && ![QQApi isQQInstalled] && [WeiboSDK isWeiboAppInstalled]) {
        button1.hidden = YES;
        button2.hidden = YES;
        button3.transform = CGAffineTransformMakeTranslation(-100, 0);
    }
    //仅安装微信、qq
    if ([WXApi isWXAppInstalled] && [QQApi isQQInstalled] && ![WeiboSDK isWeiboAppInstalled]) {
        button1.transform = CGAffineTransformMakeTranslation(50, 0);
        button2.transform = CGAffineTransformMakeTranslation(50, 0);
        button3.hidden = YES;
    }
    //仅安装微信、微博
    if ([WXApi isWXAppInstalled] && ![QQApi isQQInstalled] && [WeiboSDK isWeiboAppInstalled]) {
        button1.transform = CGAffineTransformMakeTranslation(50, 0);
        button3.transform = CGAffineTransformMakeTranslation(-50, 0);
        button2.hidden = YES;
    }
    //仅安装qq、微博
    if (![WXApi isWXAppInstalled] && [QQApi isQQInstalled] && [WeiboSDK isWeiboAppInstalled]) {
        button2.transform = CGAffineTransformMakeTranslation(-50, 0);
        button3.transform = CGAffineTransformMakeTranslation(-50, 0);
        button1.hidden = YES;
    }
    //都没安装
    if (![WXApi isWXAppInstalled] && ![QQApi isQQInstalled] && ![WeiboSDK isWeiboAppInstalled]) {
        button1.hidden = YES;
        button2.hidden = YES;
        button3.hidden = YES;
    }
    
}


- (IBAction)kuaijieClick:(id)sender {
    self.isPwdLogin = YES;

}
- (IBAction)mimaClick:(id)sender {
    self.isPwdLogin = NO;
}
- (IBAction)zhiwenClick:(id)sender
{
    [self anthTouchID:@"指纹识别的测试调用" complete:^(NSString *backStr) {
        NSLog(@"输出:%@",backStr);
    }];
}

- (void) anthTouchID:(NSString *) describe complete:(void(^)(NSString *backStr)) complete
{
    //检查操作系统是否达到指纹识别要求
    if([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
        
        //检查Touch ID是否可用
        LAContext *anthContext = [[LAContext alloc]init];
        NSError *error = [[NSError alloc]init];
        
        BOOL touchIDAvailable = [anthContext canEvaluatePolicy:kLAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error];
        
        if (touchIDAvailable) {
            
            //指纹识别可用，获取验证结果
            [anthContext evaluatePolicy:kLAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:describe reply:^(BOOL success, NSError * _Nullable error) {
                
                //加入主线程中执行
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (success) {
                        
                        //验证通过
                        if (complete) {
                            complete(@"success");
                        }
                        
                    } else {
                        
                        //验证失败
                        if (complete) {
                            complete(error.localizedDescription);
                        }
                    }
                });
            }];
            
        } else {
            
            //指纹识别不可用
            if (complete) {
                complete(error.localizedDescription);
            }
        }
        
    } else {
        
        //设备操作系统版本过低
        if (complete) {
            complete(@"Device system version too low.");
        }
    }
}

- (void)setIsPwdLogin:(BOOL)isPwdLogin
{
    //为了实现验证码、密码切换时键盘变化。
    [self.textFieldNumber resignFirstResponder];
    [self.textFieldPhone resignFirstResponder];
    _isPwdLogin = isPwdLogin;
    if (isPwdLogin)
    {
        [self.bottomLine mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@0);
            make.width.equalTo(@(ScreenWidth/2.0));
            make.height.equalTo(@2);
            make.top.equalTo(@98);
        }];
        self.mobileTitle.text = @"登录名";
        self.textFieldPhone.placeholder = @"请输入手机号/账号/邮箱";
        self.textFieldtoRight.constant = 0;
        self.yanzhenmaLabel.text = @"密码";
        self.textFieldNumber.placeholder = @"6-20位字母或数字";
        self.textFieldNumber.keyboardType = UIKeyboardTypeDefault;
        self.textFieldNumber.text = @"";
        self.textFieldNumber.secureTextEntry = YES;
        self.noticeLabel.hidden = YES;
        self.verifyLine.hidden = YES;
        self.btnSMS.hidden = YES;
    }
    else
    {

        [self.bottomLine mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@(ScreenWidth/2.0));
            make.width.equalTo(@(ScreenWidth/2.0));
            make.height.equalTo(@2);
            make.top.equalTo(@98);
        }];

        self.mobileTitle.text = @"手机号";
        self.textFieldPhone.placeholder = @"请输入手机号";
        self.textFieldtoRight.constant = 100;

        self.yanzhenmaLabel.text = @"验证码";
        self.textFieldNumber.placeholder = @"请输入验证码";
        self.textFieldNumber.keyboardType = UIKeyboardTypeNumberPad;
        self.textFieldNumber.text = @"";
        self.textFieldNumber.secureTextEntry = NO;

        self.noticeLabel.hidden = NO;
        self.verifyLine.hidden = NO;
        self.btnSMS.hidden = NO;
    }
}

- (IBAction)loginAction:(id)sender {
    //第一次登陆进来
//    if ([textFieldNumber.text isEqualToString:verifyCode] == NO) {
//        ALERT_ERR_MSG(@"验证码输入错误");
//        return;
//    }
    
    [textFieldNumber resignFirstResponder];
    [textFieldPhone resignFirstResponder];
    NSDictionary *param = nil;
    if (!self.isPwdLogin)
    {
        param = [NSDictionary dictionaryWithObjectsAndKeys:
                 @"1", @"login_class",
                 textFieldPhone.text, @"mobile",
                 textFieldNumber.text, @"cvcode",
                 [AppDelegate instance].pushToken, @"token",nil];
    }
    else
    {
        param = [NSDictionary dictionaryWithObjectsAndKeys:
                 @"1", @"login_class",
                 textFieldPhone.text, @"mobile",
                 [LPUtils CCSMD5: [LPUtils CCSMD5: textFieldNumber.text] ], @"pwd",
                 [AppDelegate instance].pushToken, @"token",nil];
    }
    CommonService *service = [[CommonService alloc] init];
    
    [service getNetWorkData:param
                       Path:LOGIN_NEW
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      
                      DebugLog(@"%@", dic);
                      
                      NSNumber *code = [dic objectForKey:@"code"];
                      NSString *msg = [dic objectForKey:@"msg"];
                      
                      NSNumber *first_login = [dic objectForKey:@"first_login"];
                      firstLogin = [NSString stringWithFormat:@"%d",[first_login intValue]];
                      if ([code intValue] == 0) {
                          NSDictionary *dicUser = [dic objectForKey:@"data"];
                          UserEntity *userEntity = [UserEntity sharedInstance];
                          
                          UserEntity *userTempEntity = [[UserEntity alloc] init];
                          userTempEntity = [userTempEntity initWithAttributes:dicUser];
                          userTempEntity.session_id = [dic objectForKey:@"session_id"];
                          [userEntity deepCopy:userTempEntity];
                          userEntity.login = YES;

                          if ([firstLogin isEqualToString:@"0"] == YES) {
                              [meVC refreshView];
                              [self.navigationController popViewControllerAnimated:YES];
                              //保存用户信息
                              [[AppDelegate instance] saveUserEntity:userEntity];
                          } else {
                              MeProfileViewController *vc = [[MeProfileViewController alloc] init];
                              vc.meVC = meVC;
                              [self.navigationController popViewControllerAnimated:NO];
                              if (wrapperMainVC != nil) {
                                  [wrapperMainVC.navigationController pushViewController:vc animated:YES];
                              } else {
                                  [mainVC.navigationController pushViewController:vc animated:YES];
                              }
                          }
                       [[NSNotificationCenter defaultCenter]postNotificationName:Notification_findmeVC_refresh object:nil];
                      } else {
                          ALERT_ERR_MSG(msg);
                      }
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      DebugLog(@"%@", message);
                  }];
}

- (IBAction)doGetSMS:(id)sender {
    if ([LPUtils isValidatePhone:textFieldPhone.text] == NO) {
        ALERT_ERR_MSG(TelEnterWrong);
    } else {
        btnSMS.enabled = NO;
        timer1 = [NSTimer scheduledTimerWithTimeInterval:1
                                                  target:self
                                                selector:@selector(showRepeatButton)
                                                userInfo:nil
                                                 repeats:YES];
//        [btnSMS setBackgroundColor:[UIColor lightGrayColor]];
        [timer1 fire];
        [self getSMSData:textFieldPhone.text];
    }
}

- (IBAction)textFieldDidChange:(id)sender {
    if (textFieldNumber.text.length == 0) {
        [btnLogin setBackgroundColor:[UIColor colorWithRed:0.82 green:0.82 blue:0.82 alpha:1]];
    } else {
        [btnLogin setBackgroundColor:[UIColor colorWithRed:0.36 green:0.8 blue:0.27 alpha:1]];
    }
}

- (void) getSMSData:(NSString *)phoneNumber {
    
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           phoneNumber, @"mobile", nil];
    
    [service getNetWorkData:param
                       Path:MOBILE_PHONE_SMS
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      DebugLog(@"%@", dic);
                      
                      NSNumber *code = [dic objectForKey:@"code"];
                      NSString *msg = [dic objectForKey:@"msg"];
                      
                      if ([code intValue] != 0) {
                          ALERT_ERR_MSG(msg);
                      } else {
                          NSDictionary *verify_code = [dic objectForKey:@"Verify_code"];
                          NSNumber *numberVC = [verify_code valueForKeyPath:@"verify_code"];
                          verifyCode = [NSString stringWithFormat:@"%d", [numberVC intValue]];
                      }
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      DebugLog(@"%@", message);
                  }];
}

- (void) showRepeatButton {
    static int count = 0;
    if (count++>=60) {
        btnSMS.enabled = YES;
        [timer1 invalidate];
        count = 0;
        [btnSMS setTitle:@"获取验证码" forState:UIControlStateNormal];
//        [btnSMS setBackgroundColor:[UIColor colorWithRed:0.55 green:0.77 blue:0.2 alpha:1]];
        return;
    }
    
    [btnSMS setTitle:[NSString stringWithFormat:@"%i秒可重发",60-count] forState:UIControlStateNormal];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [textFieldNumber resignFirstResponder];
    [textFieldPhone resignFirstResponder];
}

- (IBAction)doBackHome:(id)sender {
    if (mainVC != nil) {
        [mainVC.navigationController popViewControllerAnimated:YES];
    } else if (wrapperMainVC != nil){
        [wrapperMainVC.navigationController popViewControllerAnimated:YES];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (IBAction)registerClick:(id)sender
{
    RegisterViewController *mvc = [[RegisterViewController alloc]init];
    [self.navigationController pushViewController:mvc animated:YES];
}

- (IBAction)loginWeChat:(id)sender
{
    [ShareSDK getUserInfo:SSDKPlatformTypeWechat onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error) {
        NSLog(@"state = %ld",state);
        NSLog(@"user = %@",user);
        NSLog(@"error = %@",error);
        if (state == SSDKResponseStateSuccess)
        {
            [self socialLogin:WeChatLogin andSSDKUser:user];

        }
    }];
}

- (IBAction)loginQQ:(id)sender
{
    [ShareSDK getUserInfo:SSDKPlatformTypeQQ onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error) {
        if (state == SSDKResponseStateSuccess)
        {
            
            NSLog(@"uid=%@",user.uid);
            NSLog(@"%@",user.credential);
            NSLog(@"token=%@",user.credential.token);
            NSLog(@"nickname=%@",user.nickname);
            　　　　　　　　//在这里面实现app界面的跳转：
            　　　　　　　　//1.如果用户将qq和app已经进行了绑定，直接登录成功就能拿到用户的数据；
            　　　　　　　　//2.如果用户没有将qq和app进行绑定，那么绑定成功后就会从服务器获取到token，这个token是用来获取用户数据的，很重要。
            　　　　　　　　//总之：每一个用户都有自己唯一的标识，使用第三方登录，第三方是不知道用户的账号和密码的，那么用户必须先绑定，绑定成功后，服务器返回这个标识，之后服务器通过这个标识才能获取到用户的数据。
            [self socialLogin:QQLogin andSSDKUser:user];
        }
        else { NSLog(@"%@",error); } }];
}

- (IBAction)loginSina:(id)sender
{
    [ShareSDK getUserInfo:SSDKPlatformTypeSinaWeibo onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error) {
        NSLog(@"state = %ld",state);
        NSLog(@"user = %@",user.credential);
        NSLog(@"error = %@",error);
        if (state == SSDKResponseStateSuccess)
        {
            [self socialLogin:WeiBoLogin andSSDKUser:user];
            
        }
    }];
}

- (void)socialLogin:(SocialLoginType)type andSSDKUser:(SSDKUser*)user
{
    NSDictionary *param = nil;
    [self showLoadingView:YES];
    if (type == QQLogin) {
        param = [NSDictionary dictionaryWithObjectsAndKeys:
                 @"2", @"login_class",
                 user.uid, @"uid",
                 user.nickname, @"nickname",
                 user.icon, @"pic_head",
                 [AppDelegate instance].pushToken, @"token",nil];
    }
    if (type == WeChatLogin) {
        param = [NSDictionary dictionaryWithObjectsAndKeys:
                 @"3", @"login_class",
                 user.uid, @"uid",
                 user.nickname, @"nickname",
                 user.icon, @"pic_head",
                 [AppDelegate instance].pushToken, @"token",nil];
    }    if (type == WeiBoLogin) {
        param = [NSDictionary dictionaryWithObjectsAndKeys:
                 @"4", @"login_class",
                 user.uid, @"uid",
                 user.nickname, @"nickname",
                 user.icon, @"pic_head",
                 [AppDelegate instance].pushToken, @"token",nil];
    }
    CommonService *service = [[CommonService alloc] init];
    [service getNetWorkData:param
                       Path:LOGIN_NEW
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      [self showLoadingView:NO];

                      DebugLog(@"%@", dic);
                      
                      NSNumber *code = [dic objectForKey:@"code"];
                      NSString *msg = [dic objectForKey:@"msg"];
                      
                      NSNumber *first_login = [dic objectForKey:@"first_login"];
                      
                      firstLogin = [NSString stringWithFormat:@"%d",[first_login intValue]];
                      if ([code intValue] == 0) {
                          NSDictionary *dicUser = [dic objectForKey:@"data"];
                          UserEntity *userEntity = [UserEntity sharedInstance];
                          NSNumber *phoneBound = [dicUser objectForKey:@"phoneBound"];
                          if (![phoneBound intValue]) {
                              BindMobileViewController *mvc = [[BindMobileViewController alloc]init];
                              mvc.session_id = [dic objectForKey:@"session_id"];
                              [self.navigationController pushViewController:mvc animated:YES];
                              return;
                          }
                          UserEntity *userTempEntity = [[UserEntity alloc] init];
                          userTempEntity = [userTempEntity initWithAttributes:dicUser];
                          userTempEntity.session_id = [dic objectForKey:@"session_id"];
                          [userEntity deepCopy:userTempEntity];
                          userEntity.login = YES;
                          
                          if ([firstLogin isEqualToString:@"0"] == YES) {
                              [meVC refreshView];
                              [self.navigationController popViewControllerAnimated:YES];
                              //保存用户信息
                              [[AppDelegate instance] saveUserEntity:userEntity];
                          } else {
                              MeProfileViewController *vc = [[MeProfileViewController alloc] init];
                              vc.meVC = meVC;
                              [self.navigationController popViewControllerAnimated:NO];
                              if (wrapperMainVC != nil) {
                                  [wrapperMainVC.navigationController pushViewController:vc animated:YES];
                              } else {
                                  [mainVC.navigationController pushViewController:vc animated:YES];
                              }
                          }
                          [[NSNotificationCenter defaultCenter]postNotificationName:Notification_findmeVC_refresh object:nil];
                      } else {
                          ALERT_ERR_MSG(msg);
                      }
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      [self showLoadingView:NO];
                      DebugLog(@"%@", message);
                  }];
}

- (IBAction)forgetPwdClick:(id)sender
{
    RessetViewController *mvc = [[RessetViewController alloc]init];
    [self.navigationController pushViewController:mvc animated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"LoginViewController"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"LoginViewController"];
}
@end







